﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.Linq;
using System.Threading;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
using System.Net;
using System.Net.Mail;

namespace Nivdal.Sponsors
{
    public partial class Signup : System.Web.UI.Page
    {
        private string SponsorsloadDirectory;
        private string SponsorsTemploadDirectory;
        public string ServerfileName = "";


        //private bool ImageChaecked = false;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                if (!(String.IsNullOrEmpty(PasswordTextBox.Text.Trim())) && !(String.IsNullOrEmpty(ConfirmPasswordTextBox.Text.Trim())))
                {
                    PasswordTextBox.Attributes["value"] = PasswordTextBox.Text;
                    ConfirmPasswordTextBox.Attributes["value"] = ConfirmPasswordTextBox.Text;

                }
            }
            this.IsImageChecked.Value = "false";
            this.IsBannerExist.Value = "false";
            this.MessageLabel.Text = "";
            EmailTextBox.Attributes["onblur"] = "checkEmailUsage(this.value);";
            SponsorsloadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "Sponsors\\SponsersLogo");
            SponsorsTemploadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "Sponsors\\SponsersTempLogo");

        }

        /// <summary>
        /// Static method that retrieves the time from the server
        /// </summary>
        /// <returns></returns>
        [System.Web.Services.WebMethod]
        public static bool IsEmailAvailable(string Email)
        {
            GetNivdalData.GetNivdalData GND = new GetNivdalData.GetNivdalData();
            try
            {
                return (GND.ReadNivdalBoolData("@Email", "NewSponsorIsEmailAvailable", Email));
            }
            catch
            {
                return false;
            }

        }


        public void test()
        {
            Response.Write("Hi");
        }

        [System.Web.Services.WebMethod]
        public static string WS_ReturnTranslatedString(string StringToTranslate)
        {
            string RerurnValue = "";
            switch (StringToTranslate)
            {
                case "EmailIsTaken":
                    RerurnValue = (Resources.SponsorsResource.NewSponsor_EmailIsTaken);
                    break;
                case "BannerFileRequire":
                    RerurnValue = (Resources.SponsorsResource.NewSponsor_BannerFileIsRequire);
                    break;
            }

            return RerurnValue;

        }


        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }

        public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }



        public System.Drawing.Bitmap ResizeImgFile(System.Drawing.Bitmap img, int width, int height)
        {

            System.Drawing.Bitmap ResizedImg = ResizeImage(img, width, height, ResizeOptions.MaxWidthAndHeight);
            return ResizedImg;

        }


        public bool CheckImgFile(string FileExtantion)
        {

            if (FileExtantion.Equals(".jpg") || (FileExtantion.Equals(".gif")) || (FileExtantion.Equals(".bmp")) || (FileExtantion.Equals(".png")))
                return true;
            else
                return false;
        }




        protected string UploadBanner(bool ToShow)
        {
            string ServerfileName = "";
            this.MessageLabel.Text = "";
            string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
            DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
            DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            int intFileSizeLimit = 2048;
            string extension = Path.GetExtension(BannerFileUpload.PostedFile.FileName);
            string filenameNoExtension = Path.GetFileNameWithoutExtension(BannerFileUpload.PostedFile.FileName);
            ServerfileName = num + extension;
            string FullUploadPath = Path.Combine(SponsorsTemploadDirectory, ServerfileName);
            string FileExtantion = (Path.GetExtension(BannerFileUpload.FileName).ToLower());
            if (CheckImgFile(FileExtantion) && BannerFileUpload.PostedFile.ContentLength / 1024 < intFileSizeLimit)
            {
                System.Drawing.Bitmap ResizedBanner = ResizeImgFile(new System.Drawing.Bitmap(BannerFileUpload.PostedFile.InputStream), 150, 150);
                try
                {
                    //ResizedTeamLogo.SetResolution(150,150);
                    ResizedBanner.SetResolution(150, 150);
                    ResizedBanner.Save(FullUploadPath);
                    if (ToShow)
                    {
                        NormalImage.Visible = true;
                        NormalImage.ImageUrl = "~/Sponsors/SponsersTempLogo/" + ServerfileName;
                        this.IsImageChecked.Value = "true";
                    }

                }
                catch (Exception err)
                {
                    this.MessageLabel.Text = err.Message + FullUploadPath + ServerfileName;

                }
            }

            else
            {
                MessageLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError + " ";
                //return "Error";

            }

            return "~/Sponsors/SponsersTempLogo/" + ServerfileName;

        }

        protected void Upload_Click(object sender, EventArgs e)
        {
            if (BannerFileUpload.HasFile)
            {
                ServerfileName = UploadBanner(true);
                //this.IsBannerExist.Value = "true";

            }
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            //string AddSponsorResult = "";
            this.NoBannerDivAlert.InnerHtml = "";
            //if (NormalImage.Visible == false && (!(BannerFileUpload.HasFile && BannerFileUpload.PostedFile != null))) //user did not check banner and  uploaded a new one
            // if (this.IsImageChecked.Value == "false" && (!(BannerFileUpload.HasFile && BannerFileUpload.PostedFile != null))) //user did not check banner and  uploaded a new one
            //this.NoBannerDivAlert.InnerHtml = "<span style=color:Red;'>*</span>";
            if (NormalImage.Visible == true) //Advertise uploaded and checked the banner
            {
                ServerfileName = NormalImage.ImageUrl;
                //Response.Write(" ServerfileName: " + ServerfileName);

            }


            else if (BannerFileUpload.HasFile && BannerFileUpload.PostedFile != null) //Advertise Uploaded the banner but did not check it
            {
                ServerfileName = UploadBanner(false);
                //Response.Write(" false: ServerfileName: " + ServerfileName);

            }
            if (ServerfileName != "")
            {
                string SponsorName = this.NameTextBox.Text.Trim();
                string Email = this.EmailTextBox.Text.Trim();
                string Password = this.PasswordTextBox.Text.Trim();
                string SecurityQuestion = this.SecurityQuestionTextBox.Text.Trim();
                string SecurityAnswer = this.SecurityAnswerTextBox.Text.Trim();
                string Link = this.LinkTextBox.Text.Trim();
                //Response.Write(" name: " + SponsorName + " Email: " + Email + " Password: " + Password + " SecurityQuestion: " + SecurityQuestion + " SecurityAnswer: " +
                //     SecurityAnswer + "Link: " + Link + " ServerfileName: " + ServerfileName);

                string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
                System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
                System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
                dbCommand.CommandText = "Nivdal_NewSponsorCreate";
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.Connection = dbConnection;

                SqlParameter dbParam_SponsorName = new SqlParameter();
                dbParam_SponsorName.ParameterName = "@Name";
                dbParam_SponsorName.Value = SponsorName;
                dbParam_SponsorName.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_SponsorName);

                SqlParameter dbParam_Email = new SqlParameter();
                dbParam_Email.ParameterName = "@Email";
                dbParam_Email.Value = Email;
                dbParam_Email.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_Email);

                SqlParameter dbParam_Password = new SqlParameter();
                dbParam_Password.ParameterName = "@Password";
                dbParam_Password.Value = Password;
                dbParam_Password.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_Password);

                SqlParameter dbParam_SecurityQuestion = new SqlParameter();
                dbParam_SecurityQuestion.ParameterName = "@SecurityQuestion";
                dbParam_SecurityQuestion.Value = SecurityQuestion;
                dbParam_SecurityQuestion.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_SecurityQuestion);

                SqlParameter dbParam_SecurityAnswer = new SqlParameter();
                dbParam_SecurityAnswer.ParameterName = "@SecurityAnswer";
                dbParam_SecurityAnswer.Value = SecurityAnswer;
                dbParam_SecurityAnswer.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_SecurityAnswer);

                SqlParameter dbParam_Banner = new SqlParameter();
                dbParam_Banner.ParameterName = "@Banner";
                dbParam_Banner.Value = ServerfileName;
                dbParam_Banner.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_Banner);

                SqlParameter dbParam_SponsorLink = new SqlParameter();
                dbParam_SponsorLink.ParameterName = "@Link";
                dbParam_SponsorLink.Value = Link;
                dbParam_SponsorLink.DbType = DbType.String;
                dbCommand.Parameters.Add(dbParam_SponsorLink);


                SqlParameter dbParam_SponsorId = new SqlParameter();
                dbParam_SponsorId.ParameterName = "@SponsorId";
                dbParam_SponsorId.Value = "";
                dbParam_SponsorId.DbType = DbType.String;
                dbParam_SponsorId.Direction = ParameterDirection.Output;
                dbParam_SponsorId.Size = 64;
                dbCommand.Parameters.Add(dbParam_SponsorId);

                SqlParameter dbParam_Answer = new SqlParameter();
                dbParam_Answer.ParameterName = "@Answer";
                dbParam_Answer.Value = "";
                dbParam_Answer.DbType = DbType.String;
                dbParam_Answer.Direction = ParameterDirection.Output;
                dbParam_Answer.Size = 64;
                dbCommand.Parameters.Add(dbParam_Answer);

                try
                {

                    dbConnection.Open();
                    dbCommand.ExecuteScalar();
                    string Answer = dbParam_Answer.Value.ToString();
                    this.MessageLabel.Text = Answer;
                }
                catch (Exception SQLDBException)
                {
                    this.MessageLabel.Text = Convert.ToString(SQLDBException);
                    return;

                }

                finally
                {
                    dbConnection.Close();
                }
            }

            else
                this.NoBannerDivAlert.InnerHtml = "<span style=color:Red;'>*</span>";

        }
    }
}